<template>
    <NormalTable
        :refresh-action="'委托头查询'"
        :tableColumns="tableColumns"
        :events="events"
        :tableAttribute="tableAttribute"
        :show-page="true"
        ref="childRef"
    >
    </NormalTable>
    <el-button-group class="bg">
        <el-space>
            <AddBtn @click="add" :formData="paramContractId"></AddBtn>
            <DelBtn @click="onDelete"></DelBtn>
        </el-space>
    </el-button-group>
    <el-dialog
        v-model="dialogUpdateVisible"
        title="委托维护"
        draggable
        destroy-on-close
        :center="true"
        width="80%"
        align-center
    >
        <Contract
            :contract_id="paramContractId"
            @create="onAdded"
            @update="onUpdated"
            @close="onCloseDialog"
        >
        </Contract>
    </el-dialog>
</template>
<script setup lang="ts" name="Contracts">
import { TableColumn } from '@/common/types/app';
import { tableColumnDefault } from '@/hooks/useTable';
import { ref, reactive } from 'vue';
import { useAppStore } from '@/store/app';
import { storeToRefs } from 'pinia';
import { initObjectProperty, transFormatter } from '@/common/tools';
import { ElMessage, ElMessageBox, FormRules } from 'element-plus';
import NormalTable from '@/components/tables/NormalTable.vue';
import { ContractModel } from '@/common/types/transpost';
import { findIndex, forEach, forEachRight, includes, omit } from 'lodash';
import { Request } from '@/app/request';
import Contract from './Contract.vue';
const childRef = ref<InstanceType<typeof NormalTable>>();
const tableAttribute = ref({
    id: 'contracts-table-contracts',
});

const { client, contractKind, cyCfs } = storeToRefs(useAppStore());
let paramContractId: number | undefined;
const dialogUpdateVisible = ref(false);

const onFormatter = (_row: any, column: any, cellValue: any) => {
    let data: { value: string | number; label: string }[];
    if (column['property'] === 'client_cod') {
        data = client.value;
    } else {
        return cellValue;
    }

    return transFormatter(cellValue, data);
};
const tableColumns = reactive<TableColumn[]>([
    {
        ...tableColumnDefault,
        order: 1,
        prop: 'client_cod',
        label: '客户',
        sortable: true,
        formatter: onFormatter,
        formFieldItemType: 'single',
        optionalValues: client.value,
        width: 150,
    },
    {
        ...tableColumnDefault,
        order: 2,
        prop: 'contract_kind',
        label: '委托类型',
        sortable: true,
        formatter: onFormatter,
        formFieldItemType: 'single',
        optionalValues: contractKind.value,
        width: 150,
    },
    {
        ...tableColumnDefault,
        order: 3,
        prop: 'bill_no',
        label: '提单号',
        sortable: true,
        width: 200,
    },
    {
        ...tableColumnDefault,
        order: 4,
        prop: 'cfs_id',
        label: '站点',
        sortable: true,
        formatter: onFormatter,
        formFieldItemType: 'single',
        optionalValues: cyCfs.value,
        width: 150,
    },
    {
        ...tableColumnDefault,
        order: 5,
        prop: 'remark',
        label: '备注',
        sortable: true,
        width: 300,
    },
]);
const add = () => {
    paramContractId = undefined;
    dialogUpdateVisible.value = true;
};
const onAdded = (data: ContractModel) => {
    childRef.value?.tableData.unshift(data);
};
const update = (row: ContractModel) => {
    paramContractId = row.id;
    dialogUpdateVisible.value = true;
};
const onUpdated = (data: ContractModel) => {
    const i = findIndex(childRef.value?.tableData, (o) => {
        return o.id === data.id;
    });
    if (i > -1) {
        Object.assign(childRef.value?.tableData[i], omit(data, ['id']));
    } else {
        ElMessage.error('修改失败');
    }
};
const onDelete = async () => {
    const rows: Array<ContractModel> =
        childRef.value?.tableRef?.getSelectionRows() || [];
    if (rows.length === 0) {
        ElMessage.info({
            message: '请选择要删除数据',
        });
        return;
    }
    const ids = Array<number>();

    forEach(rows, (v: ContractModel) => {
        ids.push(v.id as number);
    });

    const msg = '';
    const cr = await ElMessageBox.confirm(msg, '确认删除选中委托', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
    })
        .then(() => {
            return true;
        })
        .catch(() => {
            return false;
        });
    if (cr) {
        //
        const req = new Request('委托删除', { ids });
        const r = await req.post();
        if (r.code > 100) {
            forEachRight(
                childRef.value?.tableData,
                (v: ContractModel, i: number) => {
                    if (includes(ids, v.id)) {
                        childRef.value?.tableData.splice(i, 1);
                    }
                },
            );
        }
    }
};
const onCloseDialog = async (arg?: any) => {
    if (dialogUpdateVisible.value) {
        dialogUpdateVisible.value = false;
    }
};
const events = {
    'row-dblclick': update,
};
</script>
<style lang="scss" scoped>
.bg {
    margin-top: 10px;

    .btn {
        margin-right: 10px;
    }
}

.page {
    float: right;
    margin-top: 10px;
}
</style>
